#include <stdlib.h>
#include <stdio.h>
#include "comic_packer.h"
#include "debug.h"
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>


extern Evas * evas;
extern Ecore_Evas *ee;

Evas_Object * get_image_object_from_file(char *filename) {
	Evas_Object *image;
	if (!filename)  {
		error("Filename is NULL\n");
		return NULL;
	}
	image = evas_object_image_add(evas);
	if (!image) {
		error("Get image from evas failed!!\n");
		exit(EXIT_FAILURE);
	}
	evas_object_image_file_set(image, filename, NULL);
	if (evas_object_image_load_error_get(image) != EVAS_LOAD_ERROR_NONE) {
		error("Load image file %s failed!!\n",filename);
		return NULL;
	}
	return image;
}

char * 	key_generator (char *filename) {
	return strdup(filename);
}

inline int is_target_file(const char *filename) {
	return strstr(filename,".png")!=0 || strstr(filename,".PNG")!=0 || strstr(filename,".jpg")!=0 || strstr(filename,".JPG")!=0;
}

void put_file_into_eet(Eet_File *ef,char *file) {
	char *key;
	Evas_Object *obj;
	int w,h;
	int ret;
	debug("Packing file %s\n",file);
	obj = get_image_object_from_file(file);
	key = key_generator(file);
	evas_object_image_size_get(obj, &w, &h);

	ret = eet_data_image_write (ef, key, 
			evas_object_image_data_get(obj, 0), 
			w, h, 
			evas_object_image_alpha_get(obj), 
			0, COMPRESS_QUALITY, 100
			);
	
	debug("Write %d bytes\n",ret);
	evas_object_del(obj);
	free(key);
}

void traverse(Eet_File *ef, const char *directory) {
	DIR *dir;
	struct dirent *dentry;
	char filename[BUFSIZE];
	struct stat s;
	dir = opendir(directory);
	if (!dir)  {
		error("Failed to open dir %s\n",directory);
		return;
	}
	debug("traversing %s\n", directory);
	while ((dentry = readdir(dir))) {
		if (dentry->d_name[0] == '.') 
			continue;
		snprintf(filename, sizeof(filename), "%s/%s", directory, dentry->d_name);
		if (stat(filename, &s) < 0) {
			error("stat %s failed !!\n",filename);
		continue;
		}
		if (S_ISDIR(s.st_mode)) 
			traverse(ef, filename);
		else if (is_target_file(filename)) {
			put_file_into_eet(ef,filename);
		}
	}
	closedir(dir);
}

Evas_Object * get_image_object_from_eet(char *filename, char *key) {
	Evas_Object *image;
	if (!key)  {
		error("key is NULL\n");
		return NULL;
	}
	image = evas_object_image_add(evas);
	evas_object_image_file_set(image,filename,key);
	
	if (image==NULL) {
		error("Image is null\n");
		return NULL;
	}
	return image;
}

